package com.ui.mine.view;


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.base.BaseRefreshFragment;
import com.bean.LoginBean;
import com.ddd.wandemo.R;
import com.ddd.wandemo.TCPClientActivity;
import com.event.LoginEvent;
import com.google.gson.Gson;
import com.net.cookie.CookiesManager;
import com.ui.mine.presenter.LoginFragmentContract;
import com.ui.mine.presenter.LoginFragmentPresenter;
import com.util.SpUtil;
import com.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import de.hdodenhof.circleimageview.CircleImageView;

public class MineFragment extends BaseRefreshFragment<LoginFragmentPresenter> implements LoginFragmentContract.View {


    private TextView mTvTheme, mTvUserName;
    private LinearLayout mLlSearchBar;
    private ImageView mIvLoginPhone;
    private ImageView mIvLoginWx;
    private ImageView mIvLoginQq;
    private ImageView mIvLoginWb;
    private TextView mTvRegister;
    private LinearLayout mLlNight, llUserTodo;
    private CircleImageView civUserHead;
    private LinearLayout llUserHead, llChoseLogin, llUserInfo, llUserSetting;
    private String userName, password;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView() {
        mLlNight = view.findViewById(R.id.ll_night);
        mTvTheme = view.findViewById(R.id.tv_theme);
        mTvUserName = view.findViewById(R.id.tv_username);

        mTvRegister = view.findViewById(R.id.tv_register);
        mIvLoginPhone = view.findViewById(R.id.iv_login_phone);

        civUserHead = view.findViewById(R.id.civ_user_head);

        llUserHead = view.findViewById(R.id.ll_user_block);
        llChoseLogin = view.findViewById(R.id.ll_login_block);
        llUserInfo = view.findViewById(R.id.ll_user_info);
        llUserSetting = view.findViewById(R.id.ll_user_setting);

        llUserTodo = view.findViewById(R.id.ll_user_todo);

    }

    @Override
    protected void initEventAndData() {
        delayLoad = false;
        mLlNight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ThemeChangeActivity.class);
                startActivity(intent);
            }
        });
        mIvLoginPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginAndRegisterActivity.class);
                intent.putExtra("type", LoginAndRegisterActivity.LOGIN);
                startActivity(intent);
            }
        });
        mTvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginAndRegisterActivity.class);
                intent.putExtra("type", LoginAndRegisterActivity.REGISTER);
                startActivity(intent);
            }
        });


        llUserInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("注销");
                builder.setMessage("是否退出登录？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPresenter.doLogout();
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.show();
            }
        });


        llUserTodo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TodoDetailActivity.class);
                startActivity(intent);
            }
        });

        String s = SpUtil.getString("userInfo");
        if (!TextUtils.isEmpty(s)) {
            byte[] userByte = Base64.decode(s, Base64.NO_WRAP);

            String s1 = new String(userByte);

            Gson gson = new Gson();
            LoginBean loginBean = gson.fromJson(s1, LoginBean.class);
            if (loginBean != null) {
                EventBus.getDefault().post(new LoginEvent(loginBean.getUsername()));
            }
        }

        llUserSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), TCPClientActivity.class));
            }
        });
    }

    @Override
    protected void loadData() {
    }

    @Override
    protected LoginFragmentPresenter initPresenter() {
        return new LoginFragmentPresenter();
    }

    @Override
    public void onLogin(LoginBean bean) {
    }

    @Override
    public void onRegister(LoginBean bean) {

    }

    @Override
    public void onLogout() {
        EventBus.getDefault().post(new LoginEvent(""));
        SpUtil.setString("userInfo", "");
        CookiesManager.clearAllCookies();
        ToastUtil.showToast("注销成功");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleLoginState(LoginEvent loginEvent) {
        String userName = loginEvent.getUserName();
        if (!TextUtils.isEmpty(userName)) {
            llUserHead.setVisibility(View.VISIBLE);
            llChoseLogin.setVisibility(View.GONE);
            mTvUserName.setText(userName);
        } else {
            llUserHead.setVisibility(View.GONE);
            llChoseLogin.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 展示一个切换动画
     */
    private void showAnimation() {
        final View decorView = getActivity().getWindow().getDecorView();
        Bitmap cacheBitmap = getCacheBitmapFromView(decorView);
        if (decorView instanceof ViewGroup && cacheBitmap != null) {
            final View view = new View(getActivity());
            view.setBackgroundDrawable(new BitmapDrawable(getResources(), cacheBitmap));
            ViewGroup.LayoutParams layoutParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            ((ViewGroup) decorView).addView(view, layoutParam);
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f);
            objectAnimator.setDuration(3000);
            objectAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    ((ViewGroup) decorView).removeView(view);
                }
            });
            objectAnimator.start();
        }
    }

    /**
     * 获取一个 View 的缓存视图
     *
     * @param view
     * @return
     */
    private Bitmap getCacheBitmapFromView(View view) {
        final boolean drawingCacheEnabled = true;
        view.setDrawingCacheEnabled(drawingCacheEnabled);
        view.buildDrawingCache(drawingCacheEnabled);
        final Bitmap drawingCache = view.getDrawingCache();
        Bitmap bitmap;
        if (drawingCache != null) {
            bitmap = Bitmap.createBitmap(drawingCache);
            view.setDrawingCacheEnabled(false);
        } else {
            bitmap = null;
        }
        return bitmap;
    }

}
